Leetcode16——3Sum Closest

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

3Sum Closest

2. Solution

  • Brute Force
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int length = nums.size();
int sum = nums[0] + nums[1] + nums[2];
int min = abs(sum - target);
for(int i = 0; i < length; i++) {
for(int j = i + 1; j < length; j++) {
for(int k = j + 1; k < length; k++) {
int temp = nums[i] + nums[j] + nums[k];
int diff = abs(temp - target);
if(min > diff) {
min = diff;
sum = temp;
}
}
}
}
return sum;
}
};
  • sort and O(n^2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
// sort vector
sort(nums.begin(), nums.end());
int length = nums.size();
int sum = nums[0] + nums[1] + nums[2];
int min = abs(sum - target);
for(int i = 0; i < length - 2; i++) {
int left = i + 1;
int right = length - 1;
while(left < right) {
int temp = nums[i] + nums[left] + nums[right];
int diff = abs(temp - target);
if(min > diff) {
min = diff;
sum = temp;
}
if(temp < target) {
left++;
}
else if(temp > target) {
right--;
}
else {
return temp;
}
}
}
return sum;
}
};

Reference

  1. https://leetcode.com/problems/3sum-closest/description/
如果有收获,可以请我喝杯咖啡!